package com.simpleframe.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.simpleframe.exception.SimpleframeException;

public class ValidateUtil {
	/**
	 * 身份证校验位
	 */
	public static String[] CHECK_DIGIT = { "1", "0", "X", "9", "8", "7", "6",
			"5", "4", "3", "2" };
	/**
	 * 身份证加权因子
	 */
	public static int[] gene = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8,
			4, 2, 1 };

	/**
	 * 获得一个字符串的长度，一个汉字按2个长度算
	 * 
	 * @param str
	 * @return
	 */
	public static int getLengthAsLetter(String str) {
		int len = 0;
		int strLength = str.length();
		int code;
		for (int i = 0; i < strLength; i++) {
			code = str.charAt(i);
			if (code > 0 && code < 257) {
				len++;
			} else {
				len += 2;
			}
		}
		return len;
	}

	/**
	 * 判断是否为email
	 * 
	 * @param email
	 * @return 是email返回true; 不是email返回false
	 */
	public static boolean isEmail(String email) {
		if (email == null || email.equals(""))
			return false;
		Pattern pattern = Pattern
				.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
		Matcher isMail = pattern.matcher(email);
		return isMail.matches();

	}

	/**
	 * 判断字符串是否为数字
	 * 
	 * @param email
	 * @return 是数字返回true; 不是数字返回false
	 */
	public static boolean isNum(String num) {
		if (num == null || num.equals(""))
			return false;
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(num);
		return isNum.matches();
	}

	/**
	 * 判断一个字符串是否为合法的字符
	 * 
	 * @param temp
	 * @return
	 */
	public static boolean isLegalityLetter(String temp) {
		if (temp == null)
			return false;
		if (temp.equals(""))
			return true;
		Pattern pattern = Pattern.compile("^\\w+$");
		Matcher isLegalityLetter = pattern.matcher(temp);
		return isLegalityLetter.matches();

	}

	/**
	 * 将一个字符串式的日期格式转换为日期型的数据
	 * 
	 * @param temp
	 * @return
	 */
	public static Date parseString(String temp) {
		return null;
	}

	/**
	 * 获得某个日期的月上减去monthCount个月
	 * 
	 * @param date
	 * @param monthCount
	 * @return
	 */
	public static Date parseByMonthCount(Date date, Integer monthCount) {
		if (date == null)
			return null;
		if (monthCount == null)
			return null;

		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(calendar.MONTH, monthCount);
		return calendar.getTime();
	}

	/**
	 * 判断是否为用户名
	 * 
	 * @param lName
	 * @return
	 */
	public static boolean isLoginName(String lName) {
		if (lName == null || lName.equals(""))
			return false;
		Pattern pattern = Pattern.compile("^[\\w@\\.-]{8,26}$");
		Matcher isLoginName = pattern.matcher(lName);
		return isLoginName.matches();
	}

	/**
	 * 判断是否为手机号
	 */
	public static boolean isMobile(String mo) {
		if (mo == null || mo.equals(""))
			return false;
		Pattern pattern = Pattern.compile("^1[3458]\\d{9}$");
		Matcher isMobile = pattern.matcher(mo);
		return isMobile.matches();
	}
	
	/**
	 * 判断是否为QQ
	 */
	public static boolean isQQ(String qq) {
		if (qq == null || qq.equals(""))
			return false;
		Pattern pattern = Pattern.compile("^[1-9][0-9]{4,}$");
		Matcher isMobile = pattern.matcher(qq);
		return isMobile.matches();
	}
	
	/**
	 * 判断是否为网址
	 */
	public static boolean isURL(String url) {
		if (url == null || url.equals(""))
			return false;
		String  strRegex = "^((https|http|ftp|rtsp|mms)?://)"  
	         + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@  
	        + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184  
	         + "|" // 允许IP和DOMAIN（域名） 
	         + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.  
	         + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名  
	        + "[a-z]{2,6})" // first level domain- .com or .museum  
	       + "(:[0-9]{1,4})?" // 端口- :80  
	        + "((/?)|" // a slash isn't required if there is no file name  
	        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";		
		Pattern pattern = Pattern.compile(strRegex);
		Matcher isMobile = pattern.matcher(url);
		return isMobile.matches();
	}
	
	
	/**
	 * 判断固定电话是否合法
	 */
	public static boolean isTelephone(String phone) {
		if (phone == null || phone.equals(""))
			return false;
		//0\\d{2,3}(-)?\\d{7,8}  ^((0\\d{2,3})-)(\\d{7,8})(-(\\d{3,}))?$
		Pattern pattern = Pattern.compile("0\\d{2,3}(-)?\\d{7,8}");
		Matcher isMobile = pattern.matcher(phone);
		return isMobile.matches();
	}

	/**
	 * 判断MSN是否合法
	 */
	public static boolean isMsn(String msn) {
		if (msn == null || msn.equals(""))
			return false;
		Pattern pattern = Pattern.compile("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$");
		Matcher isMobile = pattern.matcher(msn);
		return isMobile.matches();
	}
	
	/**
	 * 判断邮编是否合法
	 */
	public static boolean isPostCode(String postCode) {
		if (postCode == null || postCode.equals(""))
			return false;
		//[1-9]\\d{5}(?!\\d)  ^[1-9]d{5}(?!d)$
		Pattern pattern = Pattern.compile("[1-9]\\d{5}(?!\\d)");
		Matcher isMobile = pattern.matcher(postCode);
		return isMobile.matches();
	}
	
	/**
	 * 判断是否为身份证号^(\d{15}|(\d{17}[xX\d]))$
	 */
	public static boolean isIdentityCard(String card) {
		// if(card==null||card.equals(""))return false;
		// if(card.length()!=15&&card.length()!=18)return false;
		// Pattern pattern=Pattern.compile("^(\\d{15}|(\\d{17}[xX\\d]))$");
		// Matcher isIdentityCard=pattern.matcher(card);
		// return isIdentityCard.matches();
		if (card == null || card.equals(""))
			return false;
		if (card.length() != 15 && card.length() != 18)
			return false;
		Pattern pattern = Pattern.compile("^(\\d{15}|(\\d{17}[xX\\d]))$");
		Matcher isIdentityCard = pattern.matcher(card);
		if (!isIdentityCard.matches())
			return false;
		if (card.length() == 18) {
			int yearPrefix = Integer.parseInt(card.substring(6, 8));
			if (yearPrefix < 19 || yearPrefix > 21)
				return false;// 出生日期必须大于1900年小于2100年
			int month = Integer.parseInt(card.substring(10, 12));
			if (month > 12 || month == 0)
				return false; // 验证月
			int day = Integer.parseInt(card.substring(12, 14));
			if (day > 31 || day == 0)
				return false; // 验证日
			String checkDigit = getCheckDigitFor18(card);
			if (checkDigit.equals("-1"))
				return false;
			if (checkDigit.equals(card.substring(17, 18).toUpperCase())) {
				return true;
			} else {
				return false;
			}
		} else if (card.length() == 15) {
			int month = Integer.parseInt(card.substring(8, 10));
			if (month > 12 || month == 0)
				return false; // 验证月
			int day = Integer.parseInt(card.substring(10, 12));
			if (day > 31 || day == 0)
				return false;
			return true;
		}
		return false;
	}
	
	public static boolean isVersionNumber(String number){
		if (number == null || number.equals(""))
			return false;
		Pattern pattern = Pattern.compile("[0-9]+\\.[0-9]+\\.[0-9]+");
		Matcher isMobile = pattern.matcher(number);
		return isMobile.matches();
	}
	
	/**
	 * 判断 n1 是否 大于 n2
	 * @param n1
	 * @param n2
	 * @return
	 */
	public static boolean contrastVersion(String n1, String n2){
		if(!isVersionNumber(n1)
				&&!isVersionNumber(n2)){
			throw new SimpleframeException("n1 or n2 必须为gnu 格式，才可以作对比！");
		}
		String[] n1Strs = n1.split("\\.");
		String[] n2Strs = n2.split("\\.");
		
		if(Integer.valueOf(n1Strs[0]) > Integer.valueOf(n2Strs[0])){
			return true;
		}
		
		if(Integer.valueOf(n1Strs[1]) > Integer.valueOf(n2Strs[1])){
			return true;
		}
		
		if(Integer.valueOf(n1Strs[2]) > Integer.valueOf(n2Strs[2])){
			return true;
		}
		
		return false;
	}
	
	public static void main(String[] args) {
		//System.out.println(ValidateUtil.isVersionNumber("0.0.0"));
		System.out.println(ValidateUtil.contrastVersion("1.2.2", "0.3.56"));
	}
	
	

	private static String getCheckDigitFor18(String card) {
		if (card == null || card.equals(""))
			return "-1";
		int sum = 0;
		for (int i = 0; i < 17; i++) {
			sum += Integer.parseInt(card.substring(i, i + 1)) * gene[i];
		}
		return CHECK_DIGIT[sum % 11];
	}

	/**
	 * 随机字符串生成
	 * 
	 * @return
	 */
	public static String getRandmStr(int length) {
		char[] tempCs = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
				'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's',
				'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b',
				'n', 'm' };
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			sb.append(tempCs[Math.abs(random.nextInt()) % tempCs.length]);
		}
		return sb.toString();
	}
	
	/**
	 * 通过正则表达式验证参数
	 * 
	 * @param regEx-请求参数
	 * @param str-验证的字符串
	 * 
	 */
	public static Boolean regExpress(String regEx, String str) {
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);

		return m.find();
	}

}
